<template>
    <view style="height: 100%">
        <view class="pot">
            <view class="df ac sb bgcf h48 pd015">
                <p class="f14 c28">共有{{ list.length }}件商品</p>
                <p class="f14 c28" @tap.native="onEdit">{{ is_edit ? '编辑' : '完成' }}</p>
            </view>
            <view class="cart-tips">单笔订单金额满{{ beyond_price }}元免除运费</view>
        </view>

        <ul class="db">
            <block v-for="(item, index) in list" :key="index">
                <li class="df ac bgcf br12 pd15 mt12">
                    <image class="img18 mr12"  referrerPolicy='no-referrer' :src="item.is_check == 0 ? 'https://wx.xtwaixie.com/img/sel2.png' : 'https://wx.xtwaixie.com/img/sel1.png'" @tap="onIs_check" :data-i="index" />
                    <view class="f1 df">
                        <image class="img90 mr12 br8"  referrerPolicy='no-referrer' :src="item.thumb" @tap="goDetail" :data-id="item.goods_id" />
                        <view class="f1">
                            <view @tap="goDetail" :data-id="item.goods_id">
                                <h2 class="f14 c28 db f500 ovh2 w180">{{ item.title }}</h2>
                                <P class="f12 c9d db mt6">{{ item.sku_title }}</P>
                            </view>
                            <view class="df ac sb mt8">
                                <P class="f14 cff8 f600">¥{{ item.price }}</P>
                                <view class="df ac">
                                    <image
                                        class="img20"
                                        src="https://wx.xtwaixie.com/img/normal.png"
                                        @tap="onNormal"
                                        :data-size_id="item.size_id"
                                        :data-color_id="item.color_id"
                                        :data-i="index"
                                        :data-id="item.goods_id"
                                        :data-num="item.number"
                                    />
                                    <input
                                        class="add-input"
                                        :value="item.number"
                                        type="number"
                                        :data-size_id="item.size_id"
                                        :data-color_id="item.color_id"
                                        :data-i="index"
                                        :data-id="item.goods_id"
                                        @input="onItemNumber"
                                    />
                                    <image
                                        class="img20"
                                        src="https://wx.xtwaixie.com/img/add.png"
                                        :data-i="index"
                                        :data-size_id="item.size_id"
                                        :data-color_id="item.color_id"
                                        :data-id="item.goods_id"
                                        @tap="onAdd"
                                        :data-num="item.number"
                                    />
                                </view>
                            </view>
                        </view>
                    </view>
                </li>
            </block>
        </ul>

        <view class="cart-pob pd715">
            <view class="df ac sb">
                <view class="df ac" @tap="onAll_check">
                    <image class="img18"  referrerPolicy='no-referrer' :src="result.length == list.length ? 'https://wx.xtwaixie.com/img/sel1.png' : 'https://wx.xtwaixie.com/img/sel2.png'" />
                    <p class="f14 c28 ml8">全选</p>
                </view>
                <view class="df ac" v-if="is_edit">
                    <span class="f12 c28">合计</span>
                    <p class="f16 c28 f600 ml4 mr10">¥{{ totalPriceFun }}</p>
                    <button :class="'cart-but ' + (result.length != 0 ? 'bgc10' : '')" @tap="onBuy">去下单</button>
                </view>
                <button :class="'cart-but ' + (result.length != 0 ? 'bgc10' : '')" @tap="onDel" v-else>删除({{ result.length }})</button>
            </view>
        </view>
    </view>
</template>

<script>
const app = getApp();
const http = require('../../utils/http');
export default {
    data() {
        return {
            navTop: '',
            list: [],
            page: 1,
            pageSize: 10,
            pageTotal: '',
            is_edit: true,
            result: [],
            totalPrice: 0,
            beyond_price: '',
            totalPriceFun: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        this.setData({
            navTop: app.globalData.navTop
        });
        this.getList();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        onEdit() {
            this.setData({
                is_edit: !this.is_edit
            });
        },

        // 获取列表
        getList() {
            let data = {
                page: this.page,
                pageSize: this.pageSize
            };
            http.request('cart/cartList', data)
                .then((res) => {
                    res.data.list.forEach((i) => {
                        i.is_check = false;
                        this.list.push(i);
                    });
                    this.setData({
                        list: this.list,
                        pageTotal: this.pageTotal,
                        beyond_price: res.data.beyond_price
                    });
                })
                .catch((res) => {
                    uni.showToast({
                        title: res.message,
                        icon: 'none'
                    });
                });
        },

        // 单选
        onIs_check(e) {
            let i = e.currentTarget.dataset.i;
            let is_check = this.list[i].is_check;
            let result = [];
            this.setData({
                [`list[${i}].is_check`]: !is_check
            });
            this.list.forEach((i) => {
                if (i.is_check) {
                    result.push(i.id);
                }
            });
            this.setData({
                result: result
            });
            this.totalPriceFun();
        },

        // 全选
        onAll_check() {
            let list = this.list;
            let result = this.result;
            let arr = [];
            if (list.length == result.length) {
                list.forEach((i) => {
                    i.is_check = false;
                });
                this.setData({
                    list: list,
                    result: []
                });
                this.totalPriceFun();
            } else {
                list.forEach((i) => {
                    i.is_check = true;
                    arr.push(i.id);
                });
                this.setData({
                    list: list,
                    result: arr
                });
                this.totalPriceFun();
            }
        },

        //  减少
        onNormal(e) {
            let id = e.currentTarget.dataset.id;
            let i = e.currentTarget.dataset.i;
            let num = e.currentTarget.dataset.num;
            let size_id = e.currentTarget.dataset.size_id;
            let color_id = e.currentTarget.dataset.color_id;
            if (num <= 1) {
                uni.showToast({
                    title: '不能再少了~',
                    icon: 'none'
                });
            } else {
                num = num - 1;
                this.setData({
                    [`list[${i}].number`]: num
                });
                this.editCart(id, 1, 2, size_id, color_id);
            }
        },

        // 增加
        onAdd(e) {
            let id = e.currentTarget.dataset.id;
            let i = e.currentTarget.dataset.i;
            let num = e.currentTarget.dataset.num;
            let size_id = e.currentTarget.dataset.size_id;
            let color_id = e.currentTarget.dataset.color_id;
            num = num + 1;
            this.setData({
                [`list[${i}].number`]: num
            });
            this.editCart(id, 1, 1, size_id, color_id);
        },

        // 修改输入数字
        onItemNumber(e) {
            let id = e.currentTarget.dataset.id;
            let i = e.currentTarget.dataset.i;
            let num = Number(e.detail.value);
            let size_id = e.currentTarget.dataset.size_id;
            let color_id = e.currentTarget.dataset.color_id;
            this.setData({
                [`list[${i}].number`]: num
            });
            this.editCart(id, num, 3, size_id, color_id);
        },

        // 修改购物车数据
        editCart(id, num, type, size_id, color_id) {
            let data = {
                goods_id: id,
                number: num,
                type: type,
                size_id: size_id,
                color_id: color_id
            };
            http.request('cart/cartAdd', data)
                .then((res) => {
                    console.log(res);
                    this.totalPriceFun();
                })
                .catch((res) => {
                    uni.showToast({
                        title: res.message,
                        icon: 'none'
                    });
                });
        },

        // 计算总价
        totalPriceFun() {
            let totalPrice = 0;
            let listArr = this.list;
            let listNew = this.result;
            let arr = [];
            for (let i = 0; i < listArr.length; i++) {
                for (let j = 0; j < listNew.length; j++) {
                    if (listArr[i].id == listNew[j]) {
                        arr.push(listArr[i]);
                    }
                }
            }
            arr.forEach((item) => {
                totalPrice += item.number * item.price;
            });
            this.setData({
                totalPrice: totalPrice.toFixed(2)
            });
        },

        // 购买
        onBuy() {
            if (this.result.length <= 0) {
                uni.showToast({
                    title: '请先选择商品',
                    icon: 'none'
                });
                return false;
            } else {
                http.request('cart/selectCart', {
                    ids: this.result.toString()
                })
                    .then((res) => {
                        uni.navigateTo({
                            url: '/pages/order/suerOrder'
                        });
                    })
                    .catch((res) => {
                        uni.showToast({
                            title: res.message,
                            icon: 'none'
                        });
                    });
            }
        },

        // 删除
        onDel() {
            if (this.result.length <= 0) {
                uni.showToast({
                    title: '请先选择商品',
                    icon: 'none'
                });
                return false;
            } else {
                let that = this;
                uni.showModal({
                    title: '删除',
                    content: '确认删除此产品吗？',
                    success(res) {
                        if (res.confirm) {
                            that.suerDel();
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            }
        },

        suerDel() {
            http.request('cart/del', {
                ids: this.result
            })
                .then((res) => {
                    uni.showToast({
                        title: '删除成功',
                        icon: 'none'
                    });
                    this.setData({
                        list: [],
                        page: 1,
                        result: []
                    });
                    this.getList();
                })
                .catch((res) => {
                    uni.showToast({
                        title: res.message,
                        icon: 'none'
                    });
                });
        },

        // 商品详情
        goDetail(e) {
            let id = e.currentTarget.dataset.id;
            uni.navigateTo({
                url: '/pages/order/shopDetail?id=' + id
            });
        }
    }
};
</script>
<style>
@import './cart.css';
</style>
